package com.everyline.lib_base.base

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.everyline.lib_base.ext.getVmClazz
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar

/**
 * Created by on 2021/2/24.
 * 天天挂线
 *  746608431@qq.com
 *  描述:TODO
 */

abstract class BaseDBActivity<VM : BaseViewModel, DB : ViewDataBinding> : AppCompatActivity() {
    lateinit var mViewModel: VM
    lateinit var mViewBinding: DB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = DataBindingUtil.setContentView(this, getLayoutResId())
        initView(savedInstanceState)
        initViewModel()
        registerUiChange()
        initData()
        getTitleBar()


        createObserver()
        initListener()


        //统一的titlebar
        if (getTitleBar() != 0) {
            val titleBar = findViewById<TitleBar>(getTitleBar())
            titleBar.setOnTitleBarListener(object : OnTitleBarListener {
                override fun onLeftClick(v: View?) {
                    onLeftClickListener(v)
                }

                override fun onRightClick(v: View?) {
                    onRightClickListener(v)
                }

                override fun onTitleClick(v: View?) {

                }

            })
        }


    }
    abstract fun getLayoutResId(): Int
    abstract fun getTitleBar():Int
    abstract fun initView(savedInstanceState: Bundle?)
    abstract fun initData()
    abstract fun createObserver()
    abstract fun initListener()



    private fun registerUiChange() {
        mViewModel.loadingChange.showDialog.observe(this, Observer {
            showLoading()
        })
        mViewModel.loadingChange.dismissDialog.observe(this, Observer {
            dismissLoading()
        })
    }






    open fun onRightClickListener(v: View?) {}

    private fun initViewModel() {

        mViewModel = ViewModelProvider(this).get(getVmClazz(this))
    }

    open fun onLeftClickListener(v: View?) {
        finish()
    }

    abstract fun showLoading(message: String = "请求网络中...")

    abstract fun dismissLoading()
}